package com.henu.engineer.controller

import com.alibaba.fastjson.JSONObject
import com.henu.engineer.StringUtils
import com.henu.engineer.service.LoginService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

/**
 * @author noexcept
 * @date 2021/7/23 0:36
 */
@RestController
@Api("登录")
class LoginController {
    @Autowired
    lateinit var loginService: LoginService

    val logger: Logger = LoggerFactory.getLogger(javaClass)

    /**
     * 设置登录状态
     */
    @ApiOperation("login")
    @ApiResponse(code = 200, message = "登录成功")
    @PostMapping("/login")
    @CrossOrigin
    fun login(
        session: HttpSession,
        request: HttpServletRequest,
        @RequestBody jsonObject: JSONObject?
    ): String {
        val res = JSONObject()


        val id: String?
        val pwd: String?
        if (jsonObject == null) {
            res["code"] = 1
            res["msg"] = "用户名或密码为空！";
            return res.toJSONString()
        } else {
            id = jsonObject["id"] as String?
            pwd = jsonObject["pwd"] as String?
            if (StringUtils.isEmpty(id, pwd)) {
                res["code"] = 1
                res["msg"] = "用户名或密码为空！";
            }
        }
        val pair = loginService.login(session, id!!, pwd!!)

        res["msg"] = pair.second["msg"]
        res["username"] = pair.second["username"]
        res["token"] = pair.second["token"]
        res["rank"] = pair.second["rank"]
        if (pair.first) {
            res["code"] = 0
        } else {
            res["code"] = 2
        }
        return res.toJSONString()
    }

    private fun forTest(session: HttpSession): String {
        session.setAttribute("isLogged", true)
        session.setAttribute("rank", "ST")
        loginService.currentUserId = "1925060282"

        return "登录成功"
    }

}